/*
 * 版权所有：杭州领域向尚科技有限公司
 * 地址：浙江省杭州市滨江区滨安路688号天和高科技产业园5-2311
 *
 * (c) Copyright Hangzhou  Area Up Technology Co., Ltd.
 */

package org.elanfox.intellicommunity.common.resource.impl;

import org.elanfox.intellicommunity.common.constant.Constant;
import org.elanfox.intellicommunity.common.resource.StaticResourceService;
import org.elanfox.intellicommunity.common.resource.base.HttpFileResource;
import org.elanfox.intellicommunity.common.resource.vfs.VfsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 开发模式下静态资源处理
 *
 * @author allan
 * @date 04/12/2017
 */
@Service("resourceService")
@Profile(value = {Constant.PROFILE_CONTAINER})
public class LocalSharedResourceServiceImpl implements StaticResourceService {
    private final String fileHome;
    private final String urlPrefix;
    @Autowired
    private VfsHelper vfsHelper;

    public LocalSharedResourceServiceImpl() {
        fileHome = this.getClass().getResource("/").getPath();
        urlPrefix = "http://120.132.30.130:7000/dev/";
    }

    private String createConnectionString(String path) {
        return "sftp://res:res123456@120.132.30.130/data1/cdn/dev/" + path;
    }

    @Override
    public Resource upload(String path, InputStream data) throws IOException, URISyntaxException {
        File file = new File(fileHome + path);
        file.getParentFile().mkdirs();
        if (file.exists()) {
            throw new IllegalStateException("" + file.toString() + " already existing");
        }
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            StreamUtils.copy(data, outputStream);
        }
        vfsHelper.uploadBySftp(file.getAbsolutePath(), createConnectionString(path));

        return get(path);
    }

    @Override
    public Resource get(String path) throws URISyntaxException {
        String uri = urlPrefix + path;
        return new HttpFileResource(new URI(uri));
    }

    @Override
    public void delete(String path) throws IOException {

    }
}
